package com.ruoyi.web.controller.business;


import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysDictType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.dto.*;
import com.ruoyi.system.domain.vo.VoDept;
import com.ruoyi.system.domain.vo.VoUser;
import com.ruoyi.system.domain.vo.VoVehicle;
import com.ruoyi.system.domain.vo.VoVisitor;
import com.ruoyi.system.service.*;
import com.ruoyi.web.controller.websocket.WebSocketUsers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 微信信息Controller
 * 
 * @author ruoyi
 * @date 2024-04-10
 */
@RestController
@RequestMapping("/business/wechar")
public class TbWecharController extends BaseController
{
    @Autowired
    private ITbDeptService tbDeptService;
    @Autowired
    private ITbFollowerService tbFollowerService;
    @Autowired
    private ITbVisitorUserService tbVisitorUserService;
    @Autowired
    private ITbVisitorVehicleService tbVisitorVehicleService;
    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private ITbGoodsService tbGoodsService;
    @Autowired
    private IOaService oaService;
    @Autowired
    private ITbVehicleIllegalService tbVehicleIllegalService;
    @Autowired
    private ISysDictDataService dictDataService;
    @Autowired
    private ITbScreenService tbScreenService;

    @Autowired
    private ITbVehicleHisService tbVehicleHisService;

    @Autowired
    private ITbWhiteListService tbWhiteListService;

    @Autowired
    private ITbOutGoodService tbOutGoodService;

    @Autowired
    private ITbWeightTimeoutService tbWeightTimeoutService;


    private static final Logger log = LoggerFactory.getLogger(TbWecharController.class);

    @Value("${wechar.appId}")
    private String appId;

    @Value("${wechar.secret}")
    private String secret;

    /**
     * 生成二维码
     */
    @PostMapping("/get-qr")
    public AjaxResult getQr(@RequestBody QrDto dto) throws Exception {

        QrConfig config = new QrConfig(200, 200);
        String qrJpg = QrCodeUtil.generateAsBase64(dto.getCode(), config, "jpg");
        return success(qrJpg);
    }
//    public void getQr(@RequestBody String code, HttpServletResponse response) throws Exception {
//
//        response.setDateHeader("Expires", 0);
//        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
//        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
//        response.setHeader("Pragma", "no-cache");
//        response.setContentType("image/jpeg");
//
//        QrConfig config = new QrConfig(200, 200);
//        String qrJpg = QrCodeUtil.generateAsBase64(code, config, "jpg");
//
//        QrCodeUtil.generate(code, 200, 200, "jpg", response.getOutputStream());
//    }

    /**
     * 小程序证件号登录
     */
    @PostMapping("/get-openid")
    public AjaxResult getOpenId(@RequestBody WecharDto code) throws Exception {

        AjaxResult ajax = new AjaxResult();

        String getAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?"
                + "appid=" + appId + "&secret=" + secret + "&code=" + code.getCode()
                + "&grant_type=authorization_code";

        String openID = "";

        URL url = new URL(getAccessTokenUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            // 解析response中的access_token和openID
            JSONObject jsonResponse = JSONObject.parseObject(response.toString());
            // String accessToken = jsonResponse.getString("access_token");
            openID = jsonResponse.getString("openid");
        }
        ajax.put("openId", openID);
        return ajax;
    }


    /**
     * 获取车辆预约信息详细信息(通过 Open ID)
     */
    @PostMapping(value = "/vehicle-openid")
    public AjaxResult getVehicleInfo(@RequestBody TbVisitorVehicle tbVisitorVehicle)
    {
        VoVehicle rlt = new VoVehicle();
        TbVisitorVehicle item = tbVisitorVehicleService.selectTbVisitorVehicleByOpenId(tbVisitorVehicle.getOpenId());
        if (item != null) {
            BeanUtils.copyProperties(item, rlt);
            TbFollower fItem = new TbFollower();
            fItem.setPid(item.getId());
            List<TbFollower> fList = tbFollowerService.selectTbFollowerList(fItem);
            rlt.setFollowerList(fList);

            TbGoods gItem = new TbGoods();
            gItem.setPid(item.getId());
            List<TbGoods> gList = tbGoodsService.selectTbGoodsList(gItem);
            if (gList != null && gList.size() > 0) {
                rlt.setGoodsList(gList);
            }

            TbOutGood ogItem = new TbOutGood();
            ogItem.setPid(item.getId());
            List<TbOutGood> ogList = tbOutGoodService.selectTbOutGoodList(ogItem);
            if (ogList != null && ogList.size() > 0) {
                int length = ogList.size();
                String outGoods = "";
                for (int i = 0; i < length; i ++) {
                    outGoods = outGoods + ogList.get(i).getImage();
                    if (i != length -1) {
                        outGoods = outGoods + ",";
                    }
                }
                rlt.setImgList(outGoods);
            }

            String customersType = rlt.getCustomersType();
            String visitorType = rlt.getVisitorType();
            rlt.setCustomersTypeName(DictUtils.getDictLabel("visitor_vehicle", customersType));
            rlt.setVisitorTypeName(DictUtils.getDictLabel(customersType, visitorType));


            if (StringUtils.isNotBlank(rlt.getCompanyTo())) {
                rlt.setCompanyToName(DictUtils.getDictLabel("visiting_unit", rlt.getCompanyTo()));
            }
            if (StringUtils.isNotBlank(rlt.getVisitingBase())) {
                rlt.setVisitingBaseName(DictUtils.getDictLabel("visiting_base", rlt.getVisitingBase()));
            }

            if (StringUtils.isNotBlank(rlt.getCommunicationRoom())) {
                rlt.setCommunicationRoomName(DictUtils.getDictLabel("in_post", rlt.getCommunicationRoom()));
            }

//            if (StringUtils.isNotBlank(rlt.getWeighingItems())) {
//                rlt.setWeighingItemsName(DictUtils.getDictLabel("weighing", rlt.getWeighingItems()));
//            }

            if (StringUtils.isNotBlank(rlt.getVehicleType())) {
                rlt.setVehicleTypeName(DictUtils.getDictLabel("vehicle_type", rlt.getVehicleType()));
            }
        }
        if (StringUtils.isBlank(rlt.getCard())) {
            rlt.setCard("");
        }
        rlt.setInTime(null);
        rlt.setOutTime(null);

        String inPrama = JSON.toJSONString(rlt);

        log.info("返回结果 {} , 请求参数  {}  ", "车辆预约", inPrama);
        return success(rlt);
    }

    /**
     * 获取访客预约信息详细信息(通过 Open ID)
     */
    @PostMapping(value = "/user-openid")
    public AjaxResult getUserInfo(@RequestBody TbVisitorUser tbVisitorUser)
    {
        TbVisitorUser rlt = tbVisitorUserService.selectTbVisitorUserByOpenId(tbVisitorUser.getOpenId());
        VoUser vo = new VoUser();
        if (rlt != null) {
            BeanUtils.copyProperties(rlt, vo);
            vo.setInTime(null);
            vo.setOutTime(null);
            String customersType = rlt.getCustomersType();
            String visitorType = rlt.getVisitorType();
            vo.setCustomersTypeName(DictUtils.getDictLabel("visitor_user", customersType));
            vo.setVisitorTypeName(DictUtils.getDictLabel(customersType, visitorType));
            if (StringUtils.isNotBlank(rlt.getCompanyTo())) {
                vo.setCompanyToName(DictUtils.getDictLabel("visiting_unit", rlt.getCompanyTo()));
            }
            if (StringUtils.isNotBlank(rlt.getVisitingBase())) {
                vo.setVisitingBaseName(DictUtils.getDictLabel("visiting_base", rlt.getVisitingBase()));
            }
        }
        return success(vo);
    }

    /**
     * 获取访客预约信息详细信息(通过 Open ID)
     */
    @PostMapping(value = "/user-list-openid")
    public AjaxResult getUserListInfo(@RequestBody TbVisitorUser tbVisitorUser)
    {

        String inPrama = JSON.toJSONString(tbVisitorUser);

        if (StringUtils.isBlank(tbVisitorUser.getOpenId())){
            return error("本网页仅能在微信公众号中打开！");
        }

        log.info("请求接口 {} , 请求参数  {}  ", "个人预约信息列表", inPrama);

        Date now = DateUtils.getNowDate();
        DtoUser search = new DtoUser();
        search.setOpenId(tbVisitorUser.getOpenId());
        search.setOutTimeFrom(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH,DateUtils.getNowDate()));
        List<TbVisitorUser> rltList = tbVisitorUserService.selectTbVisitorUserList(search);
        List<VoUser> voList = new ArrayList<VoUser>();
        if (rltList != null && rltList.size() > 0) {
            for (TbVisitorUser rlt : rltList) {
                VoUser vo = new VoUser();
                String status = rlt.getStatus();
                BeanUtils.copyProperties(rlt, vo);

                if ((rlt.getInTime().compareTo(now) <= 0 || DateUtils.timeDistanceMin(rlt.getInTime(), now) <= 10)&& rlt.getOutTime().compareTo(now) >= 0) {
                    // 当前时间正处于预约时间段的场合
                    if ("1".equals(status)) {
                        vo.setStatusName(rlt.getUserName() + "预约信息，OA审核中");
                    } else {
                        vo.setStatusName(rlt.getUserName() + "预约信息，展示二维码");
                    }
                } else {
                    vo.setIsqr("0");
                    vo.setQr("");
                    if ("1".equals(status)) {
                        vo.setStatusName(rlt.getUserName() + "预约信息，OA审核中");
                    } else if ("2".equals(status)) {
                        vo.setStatusName(rlt.getUserName() + "预约信息，OA审核通过");
                    } else if ("3".equals(status)) {
                        vo.setStatusName(rlt.getUserName() + "预约信息，OA审核未通过" + "(" + vo.getReviewInfo() + ")");
                    } else if ("5".equals(status)) {
                        vo.setStatusName(rlt.getUserName() + "预约信息，人员离场");
                    }
                }
                voList.add(vo);
            }
        }


        DtoVehicle vehicleSearch = new DtoVehicle();
        vehicleSearch.setOpenId(tbVisitorUser.getOpenId());
        vehicleSearch.setOutTimeFrom(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH,DateUtils.getNowDate()));

        List<TbVisitorVehicle> visitorList = tbVisitorVehicleService.selectTbVisitorVehicleList(vehicleSearch);
        if (!visitorList.isEmpty()) {
            for (TbVisitorVehicle rlt : visitorList) {
                VoUser vo = new VoUser();
                String status = rlt.getStatus();

                vo.setInTime(rlt.getInTime());
                vo.setOutTime(rlt.getOutTime());
                vo.setId(rlt.getId());

                vo.setIsqr("0");
                vo.setQr("");
                if ("1".equals(status)) {
                    vo.setStatusName("车辆" + rlt.getCard() + "预约信息，OA审核中");
                } else if ("2".equals(status)) {
                    vo.setStatusName("车辆" + rlt.getCard() + "预约信息，OA审核通过");
                } else if ("3".equals(status)) {
                    vo.setStatusName("车辆" + rlt.getCard() + "预约信息，OA审核未通过" + "(" + vo.getReviewInfo() + ")");
                } else if ("4".equals(status)) {
                    vo.setStatusName("车辆" + rlt.getCard() + "预约信息，车辆已入场");
                } else if ("5".equals(status)) {
                    vo.setStatusName("车辆" + rlt.getCard() + "预约信息，车辆已离场");
                }
                voList.add(vo);
            }
        }

        return success(voList);
    }

    /**
     * 新增访客预约信息
     */
    @PostMapping(value = "/add-user")
    public AjaxResult addUser(@RequestBody TbVisitorUser tbVisitorUser)
    {

//        String uuid = IdUtils.simpleUUID();
//        if (StringUtils.isBlank(tbVisitorUser.getOpenId())) {
//            tbVisitorUser.setOpenId(uuid);
//        }

        if (StringUtils.isBlank(tbVisitorUser.getOpenId())){
            return error("本网页仅能在微信公众号中打开！");
        }

        // 预约时间校验
        DtoCheckUser check = new DtoCheckUser();
        check.setOpenId(tbVisitorUser.getOpenId());
        check.setCard(tbVisitorUser.getCard());

        // 入场时间在已有预约范围内
        check.setCheckTime(tbVisitorUser.getInTime());
        List<TbVisitorUser> checkList = tbVisitorUserService.checkTbVisitorUserList(check);
        if (checkList != null && checkList.size() > 0) {
            return error("同时段已经存在预约记录，请不要重复预约");
        }

        // 出场时间在已有预约范围内
        check.setCheckTime(tbVisitorUser.getOutTime());
        checkList = tbVisitorUserService.checkTbVisitorUserList(check);
        if (checkList != null && checkList.size() > 0) {
            return error("同时段已经存在预约记录，请不要重复预约");
        }

        TbWhiteOa checkOa = new TbWhiteOa();
        checkOa.setCard(tbVisitorUser.getInterviewedNo());
        checkOa.setPinyin(tbVisitorUser.getInterviewedName());
        List<TbWhiteOa> oaList = tbWhiteListService.selectTbWhiteOaList(checkOa);
        if (oaList.isEmpty()) {
            return error("您填写的受访员工无审批权限，请确认后再申请");
        }
        
        // 创建审批流程
        String result = oaService.createUserWorkflow(tbVisitorUser);
        // 解析返回结果
        JSONObject json = JSONObject.parseObject(result);
        if (!"100".equals(json.getString("code"))) {
            return AjaxResult.error(json.getString("msg"));
        }

        JSONObject data = json.getJSONObject("data");
        tbVisitorUser.setFollowId(data.getString("requestid"));
        tbVisitorUser.setStatus("1"); // 审批中
        tbVisitorUser.setReviewInfo("");
        tbVisitorUser.setIsqr("0");
        tbVisitorUser.setQr("");
        tbVisitorUser.setDelFlag("0");

        LocalDateTime ldt = LocalDateTime.now();
        LocalDateTime todayZero = LocalDateTime.of(ldt.getYear(), ldt.getMonthValue(), ldt.getDayOfMonth(), 0, 0, 0);
        LocalDateTime todayLasr = LocalDateTime.of(ldt.getYear(), ldt.getMonthValue(), ldt.getDayOfMonth(), 23, 59, 59);

        Date dateFrom = Date.from(todayZero.atZone(ZoneId.systemDefault()).toInstant());
        Date dateTo = Date.from(todayLasr.atZone(ZoneId.systemDefault()).toInstant());

        DtoUser dtoUser = new DtoUser();
        dtoUser.setInTimeFrom(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,dateFrom));
        dtoUser.setOutTimeTo(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,dateTo));
        List<TbVisitorUser> countlist = tbVisitorUserService.selectTbVisitorUserList(dtoUser);

        if (countlist != null && countlist.size() > 0) {

            TbScreen screen = tbScreenService.selectTbScreenById(100L);
            screen.setBooking(String.valueOf(countlist.size()));
            String visited = screen.getVisited();
            if (StringUtils.isBlank(visited) || "0".equals(visited)) {
                screen.setVisitedPercentage("0");
            } else {
                BigDecimal per = new BigDecimal(visited).divide(new BigDecimal(countlist.size()), 2, BigDecimal.ROUND_HALF_UP)
                        .multiply(new BigDecimal(100));
                screen.setVisitedPercentage(per.toString());
            }
            screen.setUpdateTime(DateUtils.getNowDate());
            screen.setSound("");
            tbScreenService.updateTbScreen(screen);
        }


        WebSocketUsers.sendMessageToUsersByText("update");
        return toAjax(tbVisitorUserService.insertTbVisitorUser(tbVisitorUser));
    }

    /**
     * 新增车辆预约信息
     */
    @PostMapping(value = "/add-vehicle")
    public AjaxResult addVehicle(@RequestBody VoVehicle tbVisitorVehicle)
    {
        String inPrama = JSON.toJSONString(tbVisitorVehicle);

        log.info("请求接口 {} , 请求参数  {}  ", "车辆预约", inPrama);

        if (StringUtils.isBlank(tbVisitorVehicle.getOpenId())){
            return error("本网页仅能在微信公众号中打开！");
        }

        // 预约时间校验
        DtoCheckUser check = new DtoCheckUser();
        check.setOpenId(tbVisitorVehicle.getOpenId());
        check.setCard(tbVisitorVehicle.getCard());

        // 入场时间在已有预约范围内
        check.setCheckTime(tbVisitorVehicle.getInTime());
        List<TbVisitorVehicle> checkList = tbVisitorVehicleService.checkTbVisitorVehicleList(check);
        if (checkList != null && checkList.size() > 0) {
            return error("同时段已经存在预约记录，请不要重复预约");
        }

        // 出场时间在已有预约范围内
        check.setCheckTime(tbVisitorVehicle.getOutTime());
        checkList = tbVisitorVehicleService.checkTbVisitorVehicleList(check);
        if (checkList != null && checkList.size() > 0) {
            return error("同时段已经存在预约记录，请不要重复预约");
        }


        TbWhiteOa checkOa = new TbWhiteOa();
        checkOa.setCard(tbVisitorVehicle.getInterviewedNo());
        checkOa.setPinyin(tbVisitorVehicle.getInterviewedName());
        List<TbWhiteOa> oaList = tbWhiteListService.selectTbWhiteOaList(checkOa);
        if (oaList.isEmpty()) {
            return error("您填写的受访员工无审批权限，请确认后再申请");
        }


//        String uuid = IdUtils.simpleUUID();
//        if (StringUtils.isBlank(tbVisitorVehicle.getOpenId())) {
//            tbVisitorVehicle.setOpenId(uuid);
//        }
        // 创建审批流程
        String result = oaService.createVehicleWorkflow(tbVisitorVehicle);
        // 解析返回结果
        JSONObject json = JSONObject.parseObject(result);
        if (!"100".equals(json.getString("code"))) {
            return AjaxResult.error(json.getString("msg"));
        }
        JSONObject data = json.getJSONObject("data");
        tbVisitorVehicle.setFollowId(data.getString("requestid"));
        tbVisitorVehicle.setStatus("1"); // 审批中
        tbVisitorVehicle.setReviewInfo("");
        tbVisitorVehicle.setDelFlag("0");
        if ("0".equals(tbVisitorVehicle.getIfWeighing())) {
            // 不过磅的场合
            tbVisitorVehicle.setWeighingItems("");
            tbVisitorVehicle.setGoodsSpec("");
            tbVisitorVehicle.setUnitTrans("");
        }

        tbVisitorVehicleService.insertTbVisitorVehicle(tbVisitorVehicle);
        Long pid = tbVisitorVehicle.getId();

        if (!"0".equals(tbVisitorVehicle.getIfWeighing())) {
            // 过磅的场合
            if (StringUtils.isNotBlank(tbVisitorVehicle.getImgList())) {

                String[] imgArr = tbVisitorVehicle.getImgList().split(",");

                for (String img : imgArr) {
                    TbOutGood tbOutGood = new TbOutGood();
                    tbOutGood.setPid(pid);
                    tbOutGood.setFlag("0"); // 入场
                    tbOutGood.setImage(img);
                    tbOutGoodService.insertTbOutGood(tbOutGood);
                }
            }
        }

        if ("1".equals(tbVisitorVehicle.getIfFollower())) {
            List<TbFollower> followerList = tbVisitorVehicle.getFollowerList();
            if (followerList != null && followerList.size() > 0) {
                for (TbFollower item : followerList) {
                    item.setPid(pid);
                    tbFollowerService.insertTbFollower(item);
                }
            }
        }

        if ("1".equals(tbVisitorVehicle.getIfGoods())) {
            List<TbGoods> goodsList = tbVisitorVehicle.getGoodsList();
            if (goodsList != null && goodsList.size() > 0) {
                for (TbGoods item : goodsList) {
                    item.setPid(pid);
                    String imgs = item.getPhoto();
                    if (StringUtils.isNotBlank(imgs)) {
                        imgs = Arrays.stream(imgs.split(",")).filter(s -> !s.isEmpty()).reduce((a, b) -> a + "," + b).orElse("");
                    }

                    item.setPhoto(imgs);
                    tbGoodsService.insertTbGoods(item);
                }
            }
        }

        LocalDateTime ldt = LocalDateTime.now();
        LocalDateTime todayZero = LocalDateTime.of(ldt.getYear(), ldt.getMonthValue(), ldt.getDayOfMonth(), 0, 0, 0);
        LocalDateTime todayLasr = LocalDateTime.of(ldt.getYear(), ldt.getMonthValue(), ldt.getDayOfMonth(), 23, 59, 59);

        Date dateFrom = Date.from(todayZero.atZone(ZoneId.systemDefault()).toInstant());
        Date dateTo = Date.from(todayLasr.atZone(ZoneId.systemDefault()).toInstant());


        DtoVehicle dtoVehicle = new DtoVehicle();
        dtoVehicle.setInTimeFrom(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,dateFrom));
        dtoVehicle.setOutTimeTo(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,dateTo));
        List<TbVisitorVehicle> countlist = tbVisitorVehicleService.selectTbVisitorVehicleList(dtoVehicle);

        if (countlist != null && countlist.size() > 0) {

            TbScreen screen = tbScreenService.selectTbScreenById(100L);
            screen.setBookingv(String.valueOf(countlist.size()));
            String vehicles = screen.getVehicles();
            if (StringUtils.isBlank(vehicles) || "0".equals(vehicles)) {
                screen.setVehiclesPercentage("0");
            } else {
                BigDecimal per = new BigDecimal(vehicles).divide(new BigDecimal(countlist.size()), 2, BigDecimal.ROUND_HALF_UP)
                        .multiply(new BigDecimal(100));
                screen.setVehiclesPercentage(per.toString());
            }
            screen.setUpdateTime(DateUtils.getNowDate());
            screen.setSound("");
            tbScreenService.updateTbScreen(screen);
        }

        WebSocketUsers.sendMessageToUsersByText("update");
        return toAjax(1);
    }

    /**
     * 查询部门(一级下拉)(废弃暂留)
     */
    @PostMapping(value = "/get-first-dept")
    public AjaxResult getFirstStep()
    {
        return success(tbDeptService.selectFristStep());
    }

    /**
     * 查询部门(二级下拉)(废弃暂留)
     */
    @PostMapping(value = "/get-second-dept")
    public AjaxResult selectSecondStep(@RequestBody TbDept tbDept)
    {
        return success(tbDeptService.selectSecondStep(tbDept.getId()));
    }

    /**
     * 查询部门(废弃暂留)
     */
    @PostMapping(value = "/get-dept")
    public AjaxResult selectDept()
    {
        List<VoDept> depts = new ArrayList<>();

        List<TbDept> frists = tbDeptService.selectFristStep();

        if (frists != null && frists.size() > 0) {
            for (TbDept item : frists) {
                VoDept vo = new VoDept();
                vo.setDept(item.getDeptName());
                List<TbDept> seconds = tbDeptService.selectSecondStep(item.getId());
                vo.setDeptList(seconds);

                depts.add(vo);
            }
        }
        return success(depts);
    }


    /**
     * 来访事由（废弃暂留）
     */
    @PostMapping(value = "/get-visitor")
    public AjaxResult selectVisitor()
    {
        List<SysDictData> firtStep = DictUtils.getDictCache("customers_type");
        List<VoVisitor> rltList = new ArrayList<>();
        for (SysDictData item : firtStep) {

            VoVisitor vo = new VoVisitor();
            String value = item.getDictValue();
            vo.setId(value);
            vo.setText(item.getDictLabel());

            List<SysDictData> secondStep = new ArrayList<>();
            List<VoVisitor.Sub> subList = new ArrayList<>();
            if ("0".equals(value)) {
                secondStep = DictUtils.getDictCache("user_type");
            } else {
                secondStep = DictUtils.getDictCache("work_visitor");
            }
            for (SysDictData item2 : secondStep) {
                VoVisitor.Sub sub = new VoVisitor.Sub();
                sub.setId(item2.getDictValue());
                sub.setText(item2.getDictLabel());
                subList.add(sub);
            }
            vo.setChildren(subList);
            rltList.add(vo);
        }
        return success(rltList);
    }

    /**
     * 访客用来访事由
     */
    @PostMapping(value = "/get-user-visitor")
    public AjaxResult selectUserVisitor()
    {
        List<SysDictData> firtStep = DictUtils.getDictCache("visitor_user");
        List<VoVisitor> rltList = new ArrayList<>();
        for (SysDictData item : firtStep) {

            VoVisitor vo = new VoVisitor();
            String value = item.getDictValue();
            vo.setId(value);
            vo.setText(item.getDictLabel());

            List<VoVisitor.Sub> subList = new ArrayList<>();
            List<SysDictData> secondStep = DictUtils.getDictCache(value);
            for (SysDictData item2 : secondStep) {
                VoVisitor.Sub sub = new VoVisitor.Sub();
                sub.setId(item2.getDictValue());
                sub.setText(item2.getDictLabel());
                subList.add(sub);
            }
            vo.setChildren(subList);
            rltList.add(vo);
        }
        return success(rltList);
    }

    /**
     * 车辆用来访事由
     */
    @PostMapping(value = "/get-vehicle-visitor")
    public AjaxResult selectVehicleVisitor()
    {
        List<SysDictData> firtStep = DictUtils.getDictCache("visitor_vehicle");
        List<VoVisitor> rltList = new ArrayList<>();
        for (SysDictData item : firtStep) {

            VoVisitor vo = new VoVisitor();
            String value = item.getDictValue();
            vo.setId(value);
            vo.setText(item.getDictLabel());

            List<VoVisitor.Sub> subList = new ArrayList<>();
            List<SysDictData> secondStep = DictUtils.getDictCache(value);
            for (SysDictData item2 : secondStep) {
                VoVisitor.Sub sub = new VoVisitor.Sub();
                sub.setId(item2.getDictValue());
                sub.setText(item2.getDictLabel());
                subList.add(sub);
            }
            vo.setChildren(subList);
            rltList.add(vo);
        }
        return success(rltList);
    }

    /**
     * 上传文件（免密2）
     */
    @PostMapping("/upload-card")
    public AjaxResult uploadCard(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            // http://ps.jhm.com.cn:8890/prod-api/profile/upload/2024/05/08/MH-SU65-RN8L_20240508194144A001.xls
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            String staticUrl = "http://ps.jhm.com.cn:8890/prod-api" + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", staticUrl);
//            ajax.put("fileName", fileName);
//            ajax.put("newFileName", FileUtils.getName(fileName));
//            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 查询字典表（免密）
     */
    @PostMapping(value = "/dict-list")
    public AjaxResult selectDictlist(@RequestBody SysDictType data)
    {
        return success(DictUtils.getDictCache(data.getDictType()));
    }

    /**
     * 车辆入场
     */
    @PostMapping("/in-car")
    public AjaxResult inCar(CarDto param)
    {
        log.debug("-----------in-1-----------");
        AjaxResult ajax = new AjaxResult();

        String card = param.getPlate_num();

        TbScreen screenSearch = new TbScreen();
        screenSearch.setNumberplate(card);
        List<TbScreen> ckList = tbScreenService.selectTbScreenList(screenSearch);
        if (ckList!=null && ckList.size() >0) {
            ajax.put("error_num", 0);
            ajax.put("error_str", "noerror");
            return ajax;
        }

        // 大屏信息
        TbScreen screen = new TbScreen();
        screen.setId(100L);

        LocalDateTime ldt = LocalDateTime.now();
        LocalDateTime todayZero = LocalDateTime.of(ldt.getYear(), ldt.getMonthValue(), ldt.getDayOfMonth(), 0, 0, 0);
        LocalDateTime todayLasr = LocalDateTime.of(ldt.getYear(), ldt.getMonthValue(), ldt.getDayOfMonth(), 23, 59, 59);

        Date dateFrom = Date.from(todayZero.atZone(ZoneId.systemDefault()).toInstant());
        Date dateTo = Date.from(todayLasr.atZone(ZoneId.systemDefault()).toInstant());


        DtoVehicle tbVisitorVehicle = new DtoVehicle();
        tbVisitorVehicle.setInTimeFrom(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,dateFrom));
        tbVisitorVehicle.setInTimeTo(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,dateTo));

        List<TbVisitorVehicle> countlist = tbVisitorVehicleService.selectTbVisitorVehicleList(tbVisitorVehicle);
        // 今日预约车辆数
        int bookingv = countlist.size();

        tbVisitorVehicle.setCard(card);
        TbVisitorVehicle rlt = tbVisitorVehicleService.selectTbVisitorVehicleLimit(tbVisitorVehicle);

        TbVehicleHis his = new TbVehicleHis();
        his.setCard(card); // 车牌号
        his.setInOut("0"); // 入场车辆
        his.setNoteTime(DateUtils.getNowDate());

        if (rlt != null) {
            screen.setPid(0L);
            screen.setPid(rlt.getId());
            // 车牌
            screen.setNumberplate(card);
            // 姓名
            screen.setUserName(rlt.getUserName());
            // 电话
            screen.setTelephone(rlt.getPhone());
            // 来访单位
            screen.setVisiting(rlt.getCompanyFrom());
            // 驾驶证
            screen.setCard(rlt.getDrivingLicense());
            // 车辆类型
            screen.setVehicleType(dictDataService.selectDictLabel("vehicle_type", rlt.getVehicleType()));
            // 进入时间
            screen.setEntry(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, DateUtils.getNowDate()));

            // 过磅物质
            String goodStr = "";
            if (StringUtils.isNotBlank(rlt.getIfWeighing())) {
                if ("0".equals(rlt.getIfWeighing())) {
                    // 是否过磅
                    screen.setWeigh("否");
                } else{
                    // 是否过磅
                    screen.setWeigh("是");
                    // 过磅物资
                    screen.setSupplies(rlt.getWeighingItems());
                    // 物品名称
                    screen.setItemName(rlt.getWeighingItems());
//                    TbGoods gItem = new TbGoods();
//                    gItem.setPid(rlt.getId());
//                    List<TbGoods> goods = tbGoodsService.selectTbGoodsList(gItem);
//                    if (goods != null && goods.size() > 0) {
//                        for (TbGoods goodItem : goods) {
//                            goodStr = goodStr + goodItem.getGoodsName() + ",";
//                        }
//                    }
                }
            }
//            if (StringUtils.isNotBlank(goodStr)) {
//                goodStr = goodStr.substring(0, goodStr.length() - 1);
//            }

            // 是否有随行人员
            if (StringUtils.isNotBlank(rlt.getIfFollower())) {
                if ("0".equals(rlt.getIfFollower())) {
                    screen.setPersonnel("无");
                } else{
                    screen.setPersonnel("有");
                }
            }
            // 是否有携带物品
            if (StringUtils.isNotBlank(rlt.getIfGoods())) {
                if ("0".equals(rlt.getIfGoods())) {
                    screen.setBelongings("无");
                } else{
                    screen.setBelongings("有");
                }
            }

            // 来访事由
            String customersType = rlt.getCustomersType();
            String visitorType = rlt.getVisitorType();
            String customersNm = DictUtils.getDictLabel("visitor_vehicle", customersType);
            String visitorNm = DictUtils.getDictLabel(customersType, visitorType);

            if (customersNm.equals(visitorNm)) {
                screen.setReason(visitorNm);
            } else {
                screen.setReason(customersNm + "-" + visitorNm);
            }

            String status = rlt.getStatus();

            if ("3".equals(status)) {
                // OA审核未通过的场合

                // 车辆状态
                screen.setVehicleStatus("OA审核未通过 : " + rlt.getReviewInfo());


                tbVisitorVehicleService.deleteLogicTbVisitorVehicleById(rlt.getId());
            } else if ("2".equals(status)) {
                // OA审核通过的场合

                // 车辆状态
                screen.setVehicleStatus("OA审核通过");

                rlt.setStatus("4");
                rlt.setUpdateTime(DateUtils.getNowDate());
                tbVisitorVehicleService.updateTbVisitorVehicle(rlt);
            }  else if ("1".equals(status))  {
                // OA审核中

                // 车辆状态
                screen.setVehicleStatus("OA审核中");
            }

            // 毛重
            screen.setGross("");
            // 皮重
            screen.setTare("");
            // 净重
            screen.setNet("");
            screen.setSound("http://ps.jhm.com.cn:8890/prod-api/profile/upload/sound/vist-in.mp3");

            TbWhiteList whiteSearch = new TbWhiteList();
            whiteSearch.setCard(card);
            List<TbWhiteList> whiteList = tbWhiteListService.selectTbWhiteListList(whiteSearch);
            if (whiteList == null || whiteList.size() == 0) {
                TbVehicleHis hisSearch = new TbVehicleHis();
                hisSearch.setInOut("0");
                hisSearch.setIfVisite("Y");
                hisSearch.setNoteTime(DateUtils.getNowDate());
                hisSearch.setCard(card);

                List<TbVehicleHis> hisList = tbVehicleHisService.checkHisList(hisSearch);
                if (hisList == null || hisList.size() == 0) {
                    his.setIfVisite("Y");
                    his.setInTime(rlt.getInTime());
                    his.setOutTime(rlt.getOutTime());
                    his.setPid(rlt.getId());
                    tbVehicleHisService.insertTbVehicleHis(his);
                }
            }

        } else {
            // 车牌
            screen.setNumberplate(card);
            screen.setPid(0L);
            // 车辆状态
            screen.setVehicleStatus("未预约车辆");
            // 进入时间
            screen.setEntry(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, DateUtils.getNowDate()));

            // 姓名
            screen.setUserName("");
            // 电话
            screen.setTelephone("");
            // 驾驶证
            screen.setCard("");
            // 车辆类型
            screen.setVehicleType("");
            // 是否过磅
            screen.setWeigh("");
            // 过磅物资
            screen.setSupplies("");
            // 物品名称
            screen.setItemName("");
            // 是否有随行人员
            screen.setPersonnel("");
            // 是否有携带物品
            screen.setBelongings("");
            // 来访单位
            screen.setVisiting("");
            // 来访事由
            screen.setReason("");
            // 毛重
            screen.setGross("");
            // 皮重
            screen.setTare("");
            // 净重
            screen.setNet("");
            screen.setSound("http://ps.jhm.com.cn:8890/prod-api/profile/upload/sound/un-in.mp3");

            TbWhiteList whiteSearch = new TbWhiteList();
            whiteSearch.setCard(card);
            List<TbWhiteList> whiteList = tbWhiteListService.selectTbWhiteListList(whiteSearch);
            if (whiteList == null || whiteList.size() == 0) {
                TbVehicleHis hisSearch = new TbVehicleHis();
                hisSearch.setInOut("0");
                hisSearch.setIfVisite("N");
                hisSearch.setNoteTime(DateUtils.getNowDate());
                hisSearch.setCard(card);

                List<TbVehicleHis> hisList = tbVehicleHisService.checkHisList(hisSearch);
                if (hisList == null || hisList.size() == 0) {
                    his.setIfVisite("N");
                    tbVehicleHisService.insertTbVehicleHis(his);
                }
            }
        }

        // 车辆状态（0默认 1审核中 2审核通过 3审核未通过 4车辆入场 5车辆出场）
        tbVisitorVehicle.setStatus("4");
        tbVisitorVehicle.setCard(null);
        List<TbVisitorVehicle> inlist = tbVisitorVehicleService.selectTbVisitorVehicleList(tbVisitorVehicle);

        // 车辆状态（0默认 1审核中 2审核通过 3审核未通过 4车辆入场 5车辆出场）
        tbVisitorVehicle.setStatus("5");
        List<TbVisitorVehicle> outlist = tbVisitorVehicleService.selectTbVisitorVehicleList(tbVisitorVehicle);

        // 已到车辆
        int vehicles = inlist.size() + outlist.size();

        // 在场车辆
        int vehicling = inlist.size();

        screen.setBookingv(String.valueOf(bookingv));
        screen.setVehicles(String.valueOf(vehicles));
        screen.setVehicling(String.valueOf(vehicling));

        // 已到车辆
        if (vehicles != 0 && bookingv != 0) {
            BigDecimal vp = new BigDecimal(vehicles).divide(new BigDecimal(bookingv), 2, BigDecimal.ROUND_HALF_UP)
                    .multiply(new BigDecimal(100));
            screen.setVehiclesPercentage(vp.toString());
        }

        screen.setUpdateTime(DateUtils.getNowDate());
        tbScreenService.updateTbScreen(screen);

        WebSocketUsers.sendMessageToUsersByText("update");

        log.debug(param.getType());
        log.debug(param.getPlate_num());
        log.debug("-----------in-2-----------");
        ajax.put("error_num", 0);
        ajax.put("error_str", "noerror");
        return ajax;
    }

    /**
     * 车辆出厂
     */
    @PostMapping("/out-car")
    public AjaxResult outCar(CarDto param)
    {
        log.debug("-----------out-1-----------");
        AjaxResult ajax = new AjaxResult();

        String card = param.getPlate_num();

        TbScreen screenSearch = new TbScreen();
        screenSearch.setNumberplate(card);
        List<TbScreen> ckList = tbScreenService.selectTbScreenList(screenSearch);
        if (ckList!=null && ckList.size() >0) {
            TbWeightTimeout search1 = new TbWeightTimeout();
            List<TbWeightTimeout> timeOutList = tbWeightTimeoutService.selectTbWeightTimeoutList(search1);
            if (timeOutList != null && !timeOutList.isEmpty()) {
                TbWeightTimeout entity = timeOutList.get(0);
                if (!StringUtils.equals(card, entity.getLicenseNo())) {
                    ajax.put("error_num", 0);
                    ajax.put("error_str", "noerror");
                    return ajax;
                }
            }
        }

        // 大屏信息
        TbScreen screen = new TbScreen();
        screen.setId(100L);

        LocalDateTime ldt = LocalDateTime.now();
        LocalDateTime todayZero = LocalDateTime.of(ldt.getYear(), ldt.getMonthValue(), ldt.getDayOfMonth(), 0, 0, 0);
        LocalDateTime todayLasr = LocalDateTime.of(ldt.getYear(), ldt.getMonthValue(), ldt.getDayOfMonth(), 23, 59, 59);

        Date dateFrom = Date.from(todayZero.atZone(ZoneId.systemDefault()).toInstant());
        Date dateTo = Date.from(todayLasr.atZone(ZoneId.systemDefault()).toInstant());

        DtoVehicle tbVisitorVehicle = new DtoVehicle();

        tbVisitorVehicle.setInTimeFrom(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,dateFrom));
        tbVisitorVehicle.setOutTimeTo(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,dateTo));

        List<TbVisitorVehicle> countlist = tbVisitorVehicleService.selectTbVisitorVehicleList(tbVisitorVehicle);
        // 今日预约车辆数
        int bookingv = countlist.size();

        tbVisitorVehicle.setCard(card);
        TbVisitorVehicle rlt = tbVisitorVehicleService.selectTbVisitorVehicleLimit(tbVisitorVehicle);

        if (rlt == null) {
            // 昨天入场 今天离场
            LocalDateTime threeDaysAgo = ldt.minusDays(1);
            todayZero = LocalDateTime.of(threeDaysAgo.getYear(), threeDaysAgo.getMonthValue(), threeDaysAgo.getDayOfMonth(), 0, 0, 0);
            dateFrom = Date.from(todayZero.atZone(ZoneId.systemDefault()).toInstant());
            tbVisitorVehicle.setInTimeFrom(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,dateFrom));
            rlt = tbVisitorVehicleService.selectTbVisitorVehicleLimit(tbVisitorVehicle);

            if (rlt == null) {
                // 前天入场 今天离场
                threeDaysAgo = ldt.minusDays(2);
                todayZero = LocalDateTime.of(threeDaysAgo.getYear(), threeDaysAgo.getMonthValue(), threeDaysAgo.getDayOfMonth(), 0, 0, 0);
                dateFrom = Date.from(todayZero.atZone(ZoneId.systemDefault()).toInstant());
                tbVisitorVehicle.setInTimeFrom(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,dateFrom));
                rlt = tbVisitorVehicleService.selectTbVisitorVehicleLimit(tbVisitorVehicle);
            }
        }

        if (rlt == null) {
            // 今天入场 预约明天离场，但他今天就要离场
            todayZero = LocalDateTime.of(ldt.getYear(), ldt.getMonthValue(), ldt.getDayOfMonth(), 0, 0, 0);
            todayLasr = LocalDateTime.of(ldt.getYear(), ldt.getMonthValue(), ldt.getDayOfMonth(), 23, 59, 59);
            LocalDateTime threeDaysAfter = ldt.plusDays(1);
            todayLasr = LocalDateTime.of(threeDaysAfter.getYear(), threeDaysAfter.getMonthValue(), threeDaysAfter.getDayOfMonth(), 23, 59, 59);

            dateFrom = Date.from(todayZero.atZone(ZoneId.systemDefault()).toInstant());
            dateTo = Date.from(todayLasr.atZone(ZoneId.systemDefault()).toInstant());
            tbVisitorVehicle.setInTimeFrom(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,dateFrom));
            tbVisitorVehicle.setOutTimeTo(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,dateTo));
            rlt = tbVisitorVehicleService.selectTbVisitorVehicleLimit(tbVisitorVehicle);

            if (rlt == null) {
                // 今天入场 预约后天离场，但他今天就要离场
                threeDaysAfter = ldt.plusDays(2);
                todayLasr = LocalDateTime.of(threeDaysAfter.getYear(), threeDaysAfter.getMonthValue(), threeDaysAfter.getDayOfMonth(), 23, 59, 59);
                dateTo = Date.from(todayLasr.atZone(ZoneId.systemDefault()).toInstant());
                tbVisitorVehicle.setOutTimeTo(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,dateTo));
                rlt = tbVisitorVehicleService.selectTbVisitorVehicleLimit(tbVisitorVehicle);
            }
        }

        TbVehicleHis his = new TbVehicleHis();

        his.setCard(card); // 车牌号
        his.setInOut("1"); // 入场车辆
        his.setNoteTime(DateUtils.getNowDate());

        if (rlt != null) {

            screen.setPid(rlt.getId());
            // 车牌
            screen.setNumberplate(rlt.getCard());
            // 姓名
            screen.setUserName(rlt.getUserName());
            // 电话
            screen.setTelephone(rlt.getPhone());
            // 来访单位
            screen.setVisiting(rlt.getCompanyFrom());
            // 驾驶证
            screen.setCard(rlt.getDrivingLicense());
            // 车辆类型
            screen.setVehicleType(dictDataService.selectDictLabel("vehicle_type", rlt.getVehicleType()));
            // 进入时间
            screen.setEntry(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, DateUtils.getNowDate()));

            // 过磅物质
            String goodStr = "";
            if (StringUtils.isNotBlank(rlt.getIfWeighing())) {
                if ("0".equals(rlt.getIfWeighing())) {
                    // 是否过磅
                    screen.setWeigh("否");
                } else{
                    // 是否过磅
                    screen.setWeigh("是");
                    // 过磅物资
                    screen.setSupplies(rlt.getWeighingItems());
                    // 物品名称
                    screen.setItemName(rlt.getWeighingItems());
//                    TbGoods gItem = new TbGoods();
//                    gItem.setPid(rlt.getId());
//                    List<TbGoods> goods = tbGoodsService.selectTbGoodsList(gItem);
//                    if (goods != null && goods.size() > 0) {
//                        for (TbGoods goodItem : goods) {
//                            goodStr = goodStr + goodItem.getGoodsName() + ",";
//                        }
//                    }

                    // 查询过磅信息
                    TbWeighbridge weighbridge = tbVisitorVehicleService.selectWeightByVehicleId(rlt.getId());
                    if (weighbridge != null) {
                        screen.setGross(weighbridge.getGross());
                        screen.setTare(weighbridge.getTare());
                        screen.setNet(weighbridge.getNet());

                    } else {
                        screen.setGross("");
                        screen.setTare("");
                        screen.setNet("");
                    }

                    Long allToday = tbVisitorVehicleService.selectAllGrossToday();
                    if (allToday != null) {

                        screen.setGoods(allToday.toString());
                    } else {

                        screen.setGoods("0");
                    }
                }
            }

            // 是否有随行人员
            if (StringUtils.isNotBlank(rlt.getIfFollower())) {
                if ("0".equals(rlt.getIfFollower())) {
                    screen.setPersonnel("无");
                } else{
                    screen.setPersonnel("有");
                }
            }
            // 是否有携带物品
            if (StringUtils.isNotBlank(rlt.getIfGoods())) {
                if ("0".equals(rlt.getIfGoods())) {
                    screen.setBelongings("无");
                } else{
                    screen.setBelongings("有");
                }
            }

            // 来访单位
            // 来访事由
            String customersType = rlt.getCustomersType();
            String visitorType = rlt.getVisitorType();
            String customersNm = DictUtils.getDictLabel("visitor_vehicle", customersType);
            String visitorNm = DictUtils.getDictLabel(customersType, visitorType);

            if (customersNm.equals(visitorNm)) {
                screen.setReason(visitorNm);
            } else {
                screen.setReason(customersNm + "-" + visitorNm);
            }

            //------------------ 地磅超时 start------------------------------
            String vehicleStatusInfo = "";

            TbWeighbridge weighbridge = tbVisitorVehicleService.selectWeightByVehicleId(rlt.getId());
            if (weighbridge != null) {
                Date updDate = weighbridge.getUpdateTime();

                Long timeDifference = DateUtils.timeDistanceSecond(DateUtils.getNowDate(), updDate);

                String dictTimeOut = DictUtils.getDictLabel("weight_timeout", "1");
                if (StringUtils.isBlank(dictTimeOut)) {
                    dictTimeOut = "600";
                }

                if (timeDifference.compareTo(Long.valueOf(dictTimeOut)) > 0) {
                    // 地磅过磅结束到现在时间相差10分钟以上

                    TbWeightTimeout query = new TbWeightTimeout();
                    query.setVisitorVehicleId(rlt.getId());
                    List<TbWeightTimeout> timeOutList = tbWeightTimeoutService.selectTbWeightTimeoutList(query);
                    if (timeOutList.isEmpty()) {
                        // 创建审批流程
                        TbWeightTimeout weightTimeout = new TbWeightTimeout();
                        weightTimeout.setVisitorVehicleId(rlt.getId());
                        weightTimeout.setLicenseNo(rlt.getCard());
                        weightTimeout.setCarOwner(rlt.getUserName());
                        weightTimeout.setWeightTime(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, updDate));
                        weightTimeout.setInTime(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, rlt.getInTime()));
                        weightTimeout.setOutTime(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, DateUtils.getNowDate()));
                        weightTimeout.setInterviewedNo(rlt.getInterviewedNo());
                        weightTimeout.setInterviewedName(rlt.getInterviewedName());

                        String result = oaService.createWeightTimeoutWorkflow(rlt);
                        // 解析返回结果
                        JSONObject json = JSONObject.parseObject(result);
                        if ("100".equals(json.getString("code"))) {
                            JSONObject data = json.getJSONObject("data");
                            weightTimeout.setRequestId(data.getString("requestid"));
                            weightTimeout.setStatus("1"); // 审核中
                            tbWeightTimeoutService.insertTbWeightTimeout(weightTimeout);
                        }
                        vehicleStatusInfo = "过磅时间与当前时间超过10分钟，需要审批后方可离场！";
                    } else {
                        TbWeightTimeout weightTimeout = timeOutList.get(0);

                        if (!"2".equals(weightTimeout.getStatus())) {
                            vehicleStatusInfo = "过磅时间与当前时间超过10分钟，OA尚未审批结束！";
                        }
                    }
                }
            }
            //------------------ 地磅超时 end------------------------------

            String nowDate = DateUtils.getDate();
            TbVehicleIllegal searchIllegal = new TbVehicleIllegal();
            searchIllegal.setOverspeedDate(nowDate);
            searchIllegal.setLicenseNo(rlt.getCard());
            List<TbVehicleIllegal> illegalList = tbVehicleIllegalService.selectTbVehicleIllegalOverspeed(searchIllegal);
            if (illegalList != null && illegalList.size() > 0) {
                String status = illegalList.get(0).getStatus();
                if ("1".equals(status)) {
                    if (StringUtils.isBlank(vehicleStatusInfo)) {
                        vehicleStatusInfo = "存在超速处罚，QA审批中！";
                    } else {
                        vehicleStatusInfo = vehicleStatusInfo + " | 存在超速处罚，QA审批中！";
                    }
                } else {
                    if (StringUtils.isBlank(vehicleStatusInfo)) {
                        vehicleStatusInfo = "存在超速处罚，QA审批未通过！";
                    } else {
                        vehicleStatusInfo = vehicleStatusInfo + " | 存在超速处罚，QA审批未通过！";
                    }
                }
            }

            if (StringUtils.isBlank(vehicleStatusInfo)) {
                screen.setVehicleStatus("允许车辆出厂！");

                rlt.setStatus("5");
                rlt.setDelFlag("2");
                rlt.setUpdateTime(DateUtils.getNowDate());
                tbVisitorVehicleService.updateTbVisitorVehicle(rlt);
            } else {
                screen.setVehicleStatus(vehicleStatusInfo);
            }

            TbWhiteList whiteSearch = new TbWhiteList();
            whiteSearch.setCard(card);
            List<TbWhiteList> whiteList = tbWhiteListService.selectTbWhiteListList(whiteSearch);
            if (whiteList == null || whiteList.size() == 0) {
                TbVehicleHis hisSearch = new TbVehicleHis();
                hisSearch.setInOut("1");
                hisSearch.setIfVisite("Y");
                hisSearch.setNoteTime(DateUtils.getNowDate());
                hisSearch.setCard(card);

                List<TbVehicleHis> hisList = tbVehicleHisService.checkHisList(hisSearch);
                if (hisList == null || hisList.size() == 0) {
                    his.setIfVisite("Y");
                    his.setInTime(rlt.getInTime());
                    his.setOutTime(rlt.getOutTime());
                    his.setPid(rlt.getId());
                    tbVehicleHisService.insertTbVehicleHis(his);
                }
            }
            screen.setSound("http://ps.jhm.com.cn:8890/prod-api/profile/upload/sound/vist-out.mp3");
        } else {

            screen.setPid(0L);
            // 车牌
            screen.setNumberplate(card);
            // 车辆状态
            screen.setVehicleStatus("未预约车辆");
            // 进入时间
            screen.setEntry(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, DateUtils.getNowDate()));

            // 姓名
            screen.setUserName("");
            // 电话
            screen.setTelephone("");
            // 驾驶证图片
            screen.setCard("");
            // 车辆类型
            screen.setVehicleType("");
            // 是否过磅
            screen.setWeigh("");
            // 过磅物资
            screen.setSupplies("");
            // 物品名称
            screen.setItemName("");
            // 是否有随行人员
            screen.setPersonnel("");
            // 是否有携带物品
            screen.setBelongings("");
            // 来访单位
            screen.setVisiting("");
            // 来访事由
            screen.setReason("");
            // 毛重
            screen.setGross("");
            // 皮重
            screen.setTare("");
            // 净重
            screen.setNet("");
            screen.setSound("http://ps.jhm.com.cn:8890/prod-api/profile/upload/sound/un-out.mp3");

            TbWhiteList whiteSearch = new TbWhiteList();
            whiteSearch.setCard(card);
            List<TbWhiteList> whiteList = tbWhiteListService.selectTbWhiteListList(whiteSearch);
            if (whiteList == null || whiteList.size() == 0) {
                TbVehicleHis hisSearch = new TbVehicleHis();
                hisSearch.setInOut("1");
                hisSearch.setIfVisite("N");
                hisSearch.setNoteTime(DateUtils.getNowDate());
                hisSearch.setCard(card);

                List<TbVehicleHis> hisList = tbVehicleHisService.checkHisList(hisSearch);
                if (hisList == null || hisList.size() == 0) {
                    his.setIfVisite("N");
                    tbVehicleHisService.insertTbVehicleHis(his);
                }
            }
        }

        ldt = LocalDateTime.now();
        todayZero = LocalDateTime.of(ldt.getYear(), ldt.getMonthValue(), ldt.getDayOfMonth(), 0, 0, 0);
        dateFrom = Date.from(todayZero.atZone(ZoneId.systemDefault()).toInstant());
        tbVisitorVehicle.setInTimeFrom(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,dateFrom));

        // 车辆状态（0默认 1审核中 2审核通过 3审核未通过 4车辆入场 5车辆出场）
        tbVisitorVehicle.setStatus("4");
        tbVisitorVehicle.setCard(null);
        List<TbVisitorVehicle> inlist = tbVisitorVehicleService.selectTbVisitorVehicleList(tbVisitorVehicle);

        // 车辆状态（0默认 1审核中 2审核通过 3审核未通过 4车辆入场 5车辆出场）
        tbVisitorVehicle.setStatus("5");
        List<TbVisitorVehicle> outlist = tbVisitorVehicleService.selectTbVisitorVehicleList(tbVisitorVehicle);

        // 已到车辆
        int vehicles = inlist.size() + outlist.size();

        // 在场车辆
        int vehicling = inlist.size();

        screen.setBookingv(String.valueOf(bookingv));
        screen.setVehicles(String.valueOf(vehicles));
        screen.setVehicling(String.valueOf(vehicling));

        // 已到车辆
        if (vehicles != 0 && bookingv != 0) {
            BigDecimal vp = new BigDecimal(vehicles).divide(new BigDecimal(bookingv), 2, BigDecimal.ROUND_HALF_UP)
                    .multiply(new BigDecimal(100));
            screen.setVehiclesPercentage(vp.toString());
        }

        screen.setUpdateTime(DateUtils.getNowDate());
        tbScreenService.updateTbScreen(screen);
        WebSocketUsers.sendMessageToUsersByText("update");

        log.debug(param.getType());
        log.debug(param.getPlate_num());
        log.debug("-----------out-2-----------");

        ajax.put("error_num", 0);
        ajax.put("error_str", "noerror");
        return ajax;
    }

    /**
     * 上传图片
     */
    @PostMapping("/out-car-good")
    public AjaxResult screenToImg(@RequestBody DtoOutGood data)
    {
        String inPrama = JSON.toJSONString(data);

        log.info("请求接口 {} , 请求参数  {}  ", "上传离场图片", inPrama);

        List<String> list = data.getImgList();
        if (list != null && list.size() > 0) {

            for (String item : list) {
                TbOutGood outGood = new TbOutGood();

                outGood.setPid(data.getId());
                outGood.setImage(item);
                outGood.setFlag("1");
                tbOutGoodService.insertTbOutGood(outGood);
            }
        }
        WebSocketUsers.sendMessageToUsersByText("update");
        return success(1);
    }

    /**
     * WebSocket群发消息测试用方法
     */
    @PostMapping("/test")
    public void test(CarDto param)
    {
        WebSocketUsers.sendMessageToUsersByText("update");
    }
}
